<template>
  <el-upload
      v-model:file-list="fileList"
      class="upload-demo" drag
      :on-error="handleError"
      :auto-upload="false"
      :show-file-list="true">
    <el-icon class="el-icon--48px" style="margin-bottom: 20px">
      <UploadFilled/>
    </el-icon>
    <div class="el-upload__text">
      将文件拖到此处，或
      <em>点击上传</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        只能上传jpg/png文件，且不超过500kb
      </div>
    </template>
  </el-upload>
  <el-button v-if="fileList.length" style="margin-top: 16px" size="small" type="success"
             @click="handleUpload">上传到服务器
  </el-button>
  <div v-if="uploadMessage" class="upload-message"
       :class="{ 'upload-success': uploadSuccess, 'upload-error': !uploadSuccess }">
    {{ uploadMessage }}
  </div>
  <span>{{ fileList }}</span>
</template>

<script setup>
import {UploadFilled} from '@element-plus/icons-vue';
import {ref} from 'vue';
import {uploadFile} from '../api/upload'; // 引入 API 函数
import {ElMessage} from 'element-plus';

const uploadMessage = ref('');
const uploadSuccess = ref(false);
const fileList = ref([]);

let uploadInstance = null;

// ElMessage({
//   message: '上传文件只能是 JPG 或 PNG 格式!',
//   type: 'error',
// });
const handleUpload = () => {
  fileList.value.forEach((file) => {
    uploadFile(file).then(res => console.log(res)).catch(err => console.log(err));
  });
};

const handleSuccess = (response, uploadFile) => {
  // 处理上传成功后的逻辑
  uploadMessage.value = '上传成功！';
  uploadSuccess.value = true;
  console.log('上传成功:', response, uploadFile);
};

const handleError = (err) => {
  // 处理上传失败后的逻辑
  uploadMessage.value = '上传失败，请重试！';
  uploadSuccess.value = false;
  console.error('上传失败:', err);
};
</script>